/*
 * Copyright (c) 2020 - present, Inspur Genersoft Co., Ltd.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *       http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */
package com.inspur.edp.lcm.metadata.extend.action;

import com.inspur.edp.lcm.metadata.api.entity.ExtractContext;
import com.inspur.edp.lcm.metadata.api.entity.ProcessMode;
import com.inspur.edp.lcm.metadata.api.service.FileService;
import com.inspur.edp.lcm.metadata.api.service.MetadataProjectService;
import com.inspur.edp.lcm.metadata.common.FileServiceImp;
import com.inspur.edp.lcm.metadata.common.Utils;
import com.inspur.edp.lcm.metadata.spi.ExtractAction;
import io.iec.edp.caf.commons.utils.SpringBeanUtils;
import java.io.File;
import java.io.IOException;
import java.nio.file.Paths;

public class ExtractActionImpl implements ExtractAction {
    @Override
    public void extract(ExtractContext context) {
        // 提取元数据包
        extractMdpkg(context);

        if (context.getDeployType() != null && !"all".equals(context.getDeployType()) && !context.getDeployType().contains("jar")) {
            return;
        }

        // 提取java交付物
        extractJavaProduct(context);
    }

    private void extractJavaProduct(ExtractContext context) {

        String javaCodePath = Paths.get(context.getProjectPath()).resolve(Utils.getJavaProjectPath()).resolve(Utils.getCodePath()).toString();
        String deployPath = Paths.get(context.getDeployPath()).resolve(Utils.getLibsPath()).toString();

        MetadataProjectService metadataProjectService = SpringBeanUtils.getBean(MetadataProjectService.class);
        ProcessMode processMode = metadataProjectService.getProcessMode(context.getProjectPath());
        if (ProcessMode.GENERATION.equals(processMode)) {
            copyJar(javaCodePath, "api", deployPath);
            copyJar(javaCodePath, "core", deployPath);
        }

        copyJar(javaCodePath, "comp", deployPath);
    }

    private void copyJar(String javaCodePath, String module, String deployPath) {
        FileService fileService = SpringBeanUtils.getBean(FileService.class);
        String moduleJarPath = getJarPath(javaCodePath, module);
        if (moduleJarPath.isEmpty()) {
            return;
        }
        String destPath = Paths.get(deployPath).resolve(new File(moduleJarPath).getName()).toString();
        fileService.createDirectory(deployPath);
        try {
            fileService.fileCopy(moduleJarPath, destPath);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private String getJarPath(String javaCodePath, String module) {
        String targetPath = Paths.get(javaCodePath).resolve(module).resolve(Utils.getTargetPath()).toString();
        File file = new File(targetPath);
        if (file.exists()) {
            File[] files = file.listFiles((dir, name) -> name.endsWith(Utils.getJarSuffix()));
            if (files.length > 0) {
                return files[0].getPath();
            }
        }
        //todo
//        "无" + module + "jar包。"
        return "";
    }

    private void extractMdpkg(ExtractContext context) {
        String binPath = Paths.get(context.getProjectPath()).resolve(Utils.getMetadataProjPath()).resolve(Utils.getMetadataBinPath()).toString();
        File binFile = new File(binPath);
        String sourcePath = "";
        if (binFile.exists()) {
            File[] files = binFile.listFiles((dir, name) -> name.endsWith(Utils.getMetadataPackageExtension()));
            if (files.length > 0) {
                sourcePath = files[0].getPath();
            }
        }
        if (sourcePath.isEmpty()) {
            throw new RuntimeException("元数据包不存在，请先生成元数据包：" + context.getProjectPath());
        }
        String targetDir = FileServiceImp.combinePath(context.getDeployPath().replace("publish\\jstack\\apps", "publish\\metadata\\apps").replace("publish/jstack/apps", "publish/metadata/apps"), "metadata");
        String targetPath = FileServiceImp.combinePath(targetDir, new File(sourcePath).getName());
        FileService fileService = SpringBeanUtils.getBean(FileService.class);
        fileService.createDirectory(targetDir);
        try {
            fileService.fileCopy(sourcePath, targetPath);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}
